<template>
  <div id="manageQuestionView">
    <h2>管理题目</h2>
    <a-table
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        total,
        pageSize: searchParams.pageSize,
        current: searchParams.current
      }"
      @page-change="onChangePage"
    >
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="onUpdate(record)"> 修改</a-button>
          <a-button status="danger" @click="onDelete(record)"> 删除</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watchEffect } from 'vue';
import { Question, QuestionControllerService } from '../../../generated';
import message from '@arco-design/web-vue/es/message';
import { useRouter } from 'vue-router';

const dataList = ref([]);
const total = ref(0);
const searchParams = ref({
  pageSize: 2,
  current: 1
});
const router = useRouter();

const columns = [
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '标题',
    dataIndex: 'title'
  },
  {
    title: '内容',
    dataIndex: 'content'
  },
  {
    title: '标签',
    dataIndex: 'tags'
  },
  {
    title: '答案',
    dataIndex: 'answer'
  },
  {
    title: '提交数',
    dataIndex: 'submitNum'
  },
  {
    title: '通过数',
    dataIndex: 'acceptedNum'
  },
  {
    title: '用户id',
    dataIndex: 'userId'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '判题配置',
    dataIndex: 'judgeConfig'
  },
  {
    title: '判题用例',
    dataIndex: 'judgeCase'
  },
  {
    title: 'Optional',
    slotName: 'optional'
  }
];

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(searchParams.value);
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error('获取题目失败' + res.message);
  }
};

/**
 * todo watchEffect 可以监听这个里面所有的值 函数里面的值发生变化就会再次调用这个函数
 * 监听 searchParams
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时请求数据
 */
onMounted(() => {
  loadData();
});

const onChangePage = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page
  };
};

const onDelete = async (question: Question) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: question.id
  });
  if (res.code === 0) {
    message.success('删除成功');
    await loadData();
  } else {
    message.error('删除失败' + res.message);
  }
};

const onUpdate = (question: Question) => {
  router.push({
    path: '/update/question',
    query: {
      id: question.id
    }
  });
};
</script>

<style scoped>
#manageQuestionView {
}
</style>
